<template>
  <div class="random-wrap">
    <div class="random-left">
      <topic-status
        :answers-results="answersResults"
        :index="index"
        :total="total"
        :user-do-quest-num="userDoQuestNum"
        :user-quest-collect="userQuestCollect"
        :user-quest-false-num="userQuestFalseNum"
        :user-quest-true-num="userQuestTrueNum"
        @filter="filter"/>
    </div>
    <div class="random-right">
      <top-bar :total="items.length" :index="index" :answers-results="answersResults" :title="title" @save="save"/>
      <el-card v-if="item" class="random-card">
        <div class="random-gray">
          <h4>
            <span>{{ index + 1 }}.</span> <span style="display: inline-block; margin: 0 5px">[{{ item.questType }}题型]</span> <span>{{ item.title }}</span>
            <img v-if="item.titlePicUrl" :src="version + '/uploadFile/path/' + item.titlePicUrl" alt="titlePicUrl" class="random-pic">
          </h4>
          <div v-show="rightAnswer.length === 1">
            <el-radio-group v-model="checkedAnswer">
              <el-radio :class="status.optiona" label="A" class="random-block" @change="changeAnswer('optiona', 'A')">
                A.
                <span v-show="!isImage(item.optiona)">{{ item.optiona }}</span>
                <img v-if="isImage(item.optiona)" :src="version + '/uploadFile/path/' + item.optiona" alt="optiona" class="random-pic">
              </el-radio>
              <el-radio :class="status.optionb" label="B" class="random-block" @change="changeAnswer('optionb', 'B')">
                B.
                <span v-show="!isImage(item.optionb)">{{ item.optionb }}</span>
                <img v-if="isImage(item.optionb)" :src="version + '/uploadFile/path/' + item.optionb" alt="optionb" class="random-pic">
              </el-radio>
              <el-radio :class="status.optionc" label="C" class="random-block" @change="changeAnswer('optionc', 'C')">
                C.
                <span v-show="!isImage(item.optionc)">{{ item.optionc }}</span>
                <img v-if="isImage(item.optionc)" :src="version + '/uploadFile/path/' + item.optionc" alt="optionc" class="random-pic">
              </el-radio>
              <el-radio :class="status.optiond" label="D" class="random-block" @change="changeAnswer('optiond', 'D')">
                D.
                <span v-show="!isImage(item.optiond)">{{ item.optiond }}</span>
                <img v-if="isImage(item.optiond)" :src="version + '/uploadFile/path/' + item.optiond" alt="optiond" class="random-pic">
              </el-radio>
              <el-radio v-show="item.optione" :class="status.optione" label="E" class="random-block" @change="changeAnswer('optione', 'E')">
                E.
                <span v-show="!isImage(item.optione)">{{ item.optione }}</span>
                <img v-if="isImage(item.optione)" :src="version + '/uploadFile/path/' + item.optione" alt="optiond" class="random-pic">
              </el-radio>
            </el-radio-group>
          </div>
          <div v-show="rightAnswer.length > 1">
            <el-checkbox-group v-model="checkedAnswers">
              <el-checkbox :class="status.optiona" label="A" class="random-block" @change="changeAnswers('optiona', 'A')">
                A.
                <span v-show="!isImage(item.optiona)">{{ item.optiona }}</span>
                <img v-if="isImage(item.optiona)" :src="version + '/uploadFile/path/' + item.optiona" alt="optiona" class="random-pic">
              </el-checkbox>
              <el-checkbox :class="status.optionb" label="B" class="random-block" @change="changeAnswers('optionb', 'B')">
                B.
                <span v-show="!isImage(item.optionb)">{{ item.optionb }}</span>
                <img v-if="isImage(item.optionb)" :src="version + '/uploadFile/path/' + item.optionb" alt="optionb" class="random-pic">
              </el-checkbox>
              <el-checkbox :class="status.optionc" label="C" class="random-block" @change="changeAnswers('optionc', 'C')">
                C.
                <span v-show="!isImage(item.optionc)">{{ item.optionc }}</span>
                <img v-if="isImage(item.optionc)" :src="version + '/uploadFile/path/' + item.optionc" alt="optionc" class="random-pic">
              </el-checkbox>
              <el-checkbox :class="status.optiond" label="D" class="random-block" @change="changeAnswers('optiond', 'D')">
                D.
                <span v-show="!isImage(item.optiond)">{{ item.optiond }}</span>
                <img v-if="isImage(item.optiond)" :src="version + '/uploadFile/path/' + item.optiond" alt="optiond" class="random-pic">
              </el-checkbox>
              <el-checkbox v-show="item.optione" :class="status.optione" label="E" class="random-block" @change="changeAnswers('optione', 'E')">
                E.
                <span v-show="!isImage(item.optione)">{{ item.optione }}</span>
                <img v-if="isImage(item.optione)" :src="version + '/uploadFile/path/' + item.optione" alt="optiond" class="random-pic">
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="random-answer-show">
            <el-button @click="isShow = !isShow">
              <span v-show="isShow">隐藏答案</span>
              <span v-show="!isShow">显示答案</span>
            </el-button>
          </div>
          <div v-show="isShow" class="random-answer-show">
            <p>正确答案：{{ item.rightAnswer }}</p>
            <p>答案解析：{{ item.answerParse }}</p>
          </div>
        </div>
        <div style="text-align: center; margin-top: 30px">
          <el-button v-show="index !== 0" style="float: left" @click="prev">上一题</el-button>
          <el-button style="display: inline-block; width: 100px; margin: 0 auto" @click="collect">
            <span v-show="item.isCollect === 0">收藏</span>
            <span v-show="item.isCollect === 1">取消收藏</span>
          </el-button>
          <el-button v-show="index !== (items.length - 1)" style="float: right" @click="next">下一题</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import TopicStatus from '@/components/TopicStatus'
import TopBar from '@/components/TopBar'
import axios from 'axios'
import { VERSION } from '@/constants/uri'
import { resetJson } from '@/utils/reset'
const imageSuffixs = ['png', 'jpg', 'jpeg']

export default {
  components: {
    TopicStatus,
    TopBar
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    link: {
      type: String,
      default: ''
    },
    examType: {
      type: String,
      default: ''
    },
    subjectCategoryId: {
      type: String,
      default: ''
    },
    subjectChapterId: {
      type: String,
      default: ''
    },
    saveLink: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      items: [],
      item: {},
      isShow: false,
      total: 0,
      userDoQuestNum: 0,
      userQuestCollect: 0,
      userQuestFalseNum: 0,
      userQuestTrueNum: 0,
      // 选过的答案 ['A', 'B,C']
      answers: [],
      // 浏览过的每道题的状态， 是否做对或未做
      answersResults: [],
      // 正确答案
      rightAnswer: [],
      // 单选选择的答案
      checkedAnswer: '',
      // 多选选择的答案
      checkedAnswers: [],
      index: 0,
      version: VERSION,
      status: {
        optiona: '',
        optionb: '',
        optionc: '',
        optiond: '',
        optione: ''
      }
    }
  },
  mounted() {
    this.queryList()
  },
  methods: {
    /*
    *   点击上一题
    * */
    prev() {
      // 判断当前题是否正确  必须在index之前调用
      this.isCorrect()
      this.index--
      this.initAnswer()
    },
    /*
    *   点击下一题
    * */
    next() {
      // 判断当前题是否正确  必须在index之前调用
      this.isCorrect()
      this.index++
      this.initAnswer()
      if (!this.answers[this.index]) {
        this.answers[this.index] = ''
      }
    },
    /*
    *   判断当前题是否正确  必须在index变化之前调用
    * */
    isCorrect() {
      let answerResult = 0
      const beforeAnswer = this.answersResults[this.index]
      if (this.rightAnswer.length > 1) {
        if (this.checkedAnswers.length === 0) {
          answerResult = 0
        } else if (this.checkedAnswers.sort().join('') === this.rightAnswer.join('')) {
          answerResult = 1
        } else {
          answerResult = 2
        }
      } else {
        if (this.checkedAnswer === '') {
          answerResult = 0
        } else if (this.checkedAnswer === this.rightAnswer.join('')) {
          answerResult = 1
        } else {
          answerResult = 2
        }
      }
      if (beforeAnswer === answerResult) {
        return
      }

      if (answerResult === 0) {
        if (beforeAnswer === 1) {
          this.userQuestTrueNum--
        } else if (beforeAnswer === 2) {
          this.userQuestFalseNum--
        }
        this.userDoQuestNum--
      }

      if (answerResult === 1) {
        this.userQuestTrueNum++
        if (beforeAnswer === 0) {
          this.userDoQuestNum++
        }
        if (beforeAnswer === 2) {
          this.userQuestFalseNum--
        }
      }

      if (answerResult === 2) {
        this.userQuestFalseNum++
        if (beforeAnswer === 0) {
          this.userDoQuestNum++
        }
        if (beforeAnswer === 1) {
          this.userQuestTrueNum--
        }
      }

      this.answersResults[this.index] = answerResult
    },
    /*
    *   点击上一题或下一题之后初始化答案等数据
    * */
    initAnswer() {
      this.isShow = false
      this.checkedAnswer = ''
      this.checkedAnswers = []
      this.item = this.items[this.index]
      this.rightAnswer = this.item.rightAnswer.split(',')
      // 初始化选中的答案
      resetJson(this.status)
      if (this.item.rightAnswer.split(',').length > 1) {
        this.checkedAnswers = this.answers[this.index] ? this.answers[this.index] : []
        this.initStatus(this.checkedAnswers)
      } else {
        this.checkedAnswer = this.answers[this.index] ? this.answers[this.index] : ''
        this.initStatus(this.checkedAnswer)
      }
    },
    initStatus(checkedAnswers) {
      if (typeof checkedAnswers === 'string') {
        const key = 'option' + checkedAnswers.toLowerCase()
        if (checkedAnswers === this.item.rightAnswer) {
          this.status[key] = 'success'
        } else {
          this.status[key] = 'error'
        }
      } else {
        checkedAnswers.forEach(item => {
          const key = 'option' + item.toLowerCase()
          if (this.item.rightAnswer.includes(item)) {
            this.status[key] = 'success'
          } else {
            this.status[key] = 'error'
          }
        })
      }
    },
    /*
    *   收藏
    * */
    collect() {
      if (this.item.isCollect === 0) {
        axios.post('/collect/practice/' + this.item.id, {}).then(res => {
          if (res.success) {
            this.item.isCollect = 1
            this.userQuestCollect++
            this.$message({
              message: '收藏成功',
              type: 'success'
            })
          }
        })
      } else {
        axios.delete('/cancel/collect/practice/' + this.item.id).then(res => {
          if (res.success) {
            this.item.isCollect = 0
            this.userQuestCollect--
            this.$message({
              message: '取消收藏成功',
              type: 'success'
            })
          }
        })
      }
    },
    /*
   *   保存进度
   * */
    save() {
      const postData = []
      const ids = []
      this.answers.forEach((item, index) => {
        let answerResult = 0
        let type = ''
        if (typeof item === 'string') {
          type = 'string'
          if (item === '') {
            answerResult = 0
          } else if (item === this.items[index].rightAnswer) {
            answerResult = 1
          } else {
            answerResult = 2
          }
        } else {
          type = 'array'
          if (item.length === 0) {
            answerResult = 0
          } else if (item.join(',') === this.items[index].rightAnswer) {
            answerResult = 1
          } else {
            answerResult = 2
          }
        }
        ids.push(this.items[index].id)
        postData.push({
          questId: this.items[index].id,
          result: type === 'string' ? item : item.join(','),
          answerResult: answerResult
        })
      })

      this.items.forEach(item => {
        if (!ids.includes(item.id)) {
          postData.push({
            questId: item.id,
            result: null,
            answerResult: null
          })
        }
      })
      axios.post(this.saveLink, { data: postData,
        examType: this.examType,
        seq: this.index + 1,
        subjectCategoryId: this.subjectCategoryId,
        subjectChapterId: this.subjectChapterId
      }).then(res => {
        if (res.success) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        }
      })
    },
    /*
    *   答案是否是图片
    * */
    isImage(value) {
      if (!value) {
        return false
      }
      const index = value.lastIndexOf('.')
      if (!index) {
        return false
      }

      if (imageSuffixs.includes(value.substr(index + 1))) {
        return true
      }
    },
    /*
    *   选中单选题
    * */
    changeAnswer(key, value) {
      this.answers[this.index] = this.checkedAnswer
      if (this.checkedAnswer === value) {
        if (this.rightAnswer.includes(value)) {
          this.status[key] = 'success'
        } else {
          this.status[key] = 'error'
        }
      } else {
        this.status[key] = ''
      }
    },
    /*
    *   多选题选中
    * */
    changeAnswers(key, value) {
      this.answers[this.index] = this.checkedAnswers
      // 选中
      if (this.checkedAnswers.includes(value)) {
        if (this.rightAnswer.includes(value)) {
          this.status[key] = 'success'
        } else {
          this.status[key] = 'error'
        }
      } else {
        this.status[key] = ''
      }
    },
    /*
    *   获取所有题目
    * */
    filter(value) {
      let link = this.link.substr(0, this.link.length - 7)
      link += '/' + value + '/1/2000'
      axios.get(link).then(res => {
        if (!res.success) {
          return
        }
        this.index = 0
        this.items = res.data
        if (res.data.length) {
          this.item = this.items[this.index]
          this.handleResult(res)
        } else {
          this.item = null
          this.$message({
            message: '暂无数据',
            type: 'warning'
          })
        }
      })
    },
    queryList() {
      axios.get(this.link).then(res => {
        if (res.success) {
          this.index = res.seq - 1
          this.total = res.total
          this.items = res.data
          this.item = this.items[this.index]
          this.userDoQuestNum = res.userDoQuestNum
          this.userQuestCollect = res.userQuestCollect
          this.userQuestFalseNum = res.userQuestFalseNum
          this.userQuestTrueNum = res.userQuestTrueNum
          this.handleResult(res)
        }
      })
    },
    handleResult(res) {
      this.checkedAnswers = []
      this.checkedAnswer = ''
      this.rightAnswer = this.item.rightAnswer.split(',')
      if (this.item.result) {
        if (this.item.rightAnswer.length > 1) {
          this.checkedAnswers = this.item.result.split(',')
          this.initStatus(this.checkedAnswers)
        } else {
          this.checkedAnswer = this.item.result
          this.initStatus(this.checkedAnswer)
        }
      }

      this.answers = []
      this.answersResults = []
      res.data.forEach(item => {
        if (item.result) {
          if (item.rightAnswer.length > 1) {
            this.answers.push(item.result.split(','))
          } else {
            this.answers.push(item.result)
          }
        }

        this.answersResults.push(item.answerResult)
      })
    }
  }
}
</script>

<style lang="scss">
  .random-wrap {
    display: flex;
  }

  .random-left {
    width: 235px;
    height: calc(100vh - 50px);
  }

  .random-right {
    flex: 1;
  }

  .random-card {
    margin: 20px;
  }

  .random-block {
    display: block;
    margin: 10px 0 25px 0 !important;
  }

  .random-pic {
    width: 150px;
    margin-left: 20px;
    vertical-align: middle;
  }

  .success {
    .el-checkbox__input.is-checked+.el-checkbox__label, .el-radio__input.is-checked+.el-radio__label {
      color: green;
    }
  }

  .error {
    .el-checkbox__input.is-checked+.el-checkbox__label, .el-radio__input.is-checked+.el-radio__label {
      color: red;
    }
  }

  .random-answer-show {
    margin-bottom: 30px;
  }
  .random-gray {
    padding: 10px;
    background: #f0f2f5;
  }
</style>
